package com.hans.exercise

import actors._, Actor._

/**
 *
 * 计算超大数组和
 */
object SumActor {

  val nums = Array(1, 2, 6, 7, 4, 2, 3, 4, 5, 6, 5, 32, 3, 3, 4, 6, 5, 13, 9, 3, 6, 22, 5, 6, 7, 8, 19, 9, 19)

  def main(args: Array[String]): Unit = {
    //    println("begin...")
    val splits: Array[(Int, Int)] = Array((0, 10), (11, nums.length - 1))
    val caller = self
    val accumulator = actor {
      var continue = true
      var sum = 0
      println("accumulator=>" + Thread.currentThread())
      loopWhile(continue) {
        reactWithin(1000) {
          case number: Int => sum += number
          case TIMEOUT =>
            continue = false
            caller ! sum
        }
      }
    }
    val accumulator1 = actor {
      var sum = 0
      for (i <- splits(0)._1 to splits(0)._2) {
        sum += nums(i)
      }
      println("accumulator1=>" + Thread.currentThread())
      accumulator ! sum
    }
    val accumulator2 = actor {
      var sum = 0
      for (i <- splits(1)._1 to splits(1)._2) {
        sum += nums(i)
      }
      println("accumulator2=>" + Thread.currentThread())
      accumulator ! sum
    }
    println("wait...")
    receiveWithin(1000) {
      case result => println("Total is " + result)
    }
    println("end")
  }
}